<?php

class CurlClient
{
    protected $url;
    protected $options = [];
    protected $headers = [];
    protected $data = [];
    protected $method = 'GET';
    protected $timeout = 30; // 默认超时时间（秒）
    protected $connectTimeout = 10; // 默认连接超时时间（秒）
    protected $userAgent = 'CurlClient/1.0';

    public function __construct($url = null)
    {
        if ($url) {
            $this->url = $url;
        }
    }

    // 设置请求的URL
    public function setUrl($url)
    {
        $this->url = $url;
        return $this;
    }

    // 设置请求方法
    public function setMethod($method)
    {
        $this->method = strtoupper($method);
        return $this;
    }

    // 设置请求头
    public function setHeaders(array $headers)
    {
        $this->headers = $headers;
        return $this;
    }

    // 添加单个请求头
    public function addHeader($key, $value)
    {
        $this->headers[$key] = $value;
        return $this;
    }

    // 设置请求数据（POST/PUT）
    public function setData(array $data)
    {
        $this->data = $data;
        return $this;
    }

    // 设置超时时间
    public function setTimeout($timeout)
    {
        $this->timeout = $timeout;
        return $this;
    }

    // 设置连接超时时间
    public function setConnectTimeout($connectTimeout)
    {
        $this->connectTimeout = $connectTimeout;
        return $this;
    }

    // 设置User-Agent
    public function setUserAgent($userAgent)
    {
        $this->userAgent = $userAgent;
        return $this;
    }

    // 发送请求
    public function execute()
    {
        $ch = curl_init();

        // 设置URL
        curl_setopt($ch, CURLOPT_URL, $this->url);

        // 设置请求方法
        switch ($this->method) {
            case 'POST':
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $this->prepareData());
                break;
            case 'PUT':
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
                curl_setopt($ch, CURLOPT_POSTFIELDS, $this->prepareData());
                break;
            case 'DELETE':
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
                break;
            default:
                curl_setopt($ch, CURLOPT_HTTPGET, true);
                break;
        }

        // 设置超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);

        // 设置请求头
        if (!empty($this->headers)) {
            $headerArray = [];
            foreach ($this->headers as $key => $value) {
                $headerArray[] = $key . ': ' . $value;
            }
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        }

        // 设置返回数据为字符串
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // 设置User-Agent
        curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);

        // 执行请求
        $response = curl_exec($ch);

        // 检查错误
        if (curl_errno($ch)) {
            $error = curl_error($ch);
            curl_close($ch);
            throw new Exception("cURL Error: $error");
        }

        // 获取HTTP状态码
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        // 关闭cURL会话
        curl_close($ch);

        return [
            'status_code' => $httpCode,
            'response' => $response
        ];
    }

    // 准备请求数据
    protected function prepareData()
    {
        if (isset($this->headers['Content-Type']) && $this->headers['Content-Type'] === 'application/json') {
            return json_encode($this->data);
        }
        return http_build_query($this->data);
    }
}